package com.wjw.redis.stream.handler;

import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

/**
 * @author wjwei
 */
@Configuration
public class RedissonDelayTaskHandler implements Runnable {

    public RedissonDelayTaskHandler(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    private final RedissonClient redissonClient;
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run() {
        RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("orderQueue");
        // 注意虽然delayedQueue在这个方法里面没有用到，但是这行代码也是必不可少的。主要用于触发redisson内的订阅服务
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
        while (true) {
            String orderId;
            try {
                orderId = blockingDeque.take();
            } catch (Exception e) {
                System.err.println(Arrays.toString(e.getStackTrace()));
                continue;
            }
            System.err.println(LocalDateTime.now().format(dateTimeFormatter) + " 延时队列收到:" + orderId);
        }
    }
}
